namespace HZY.Framework.Core.Utils;

/// <summary>
/// 字典操作
/// </summary>
public static class DictionaryUtil
{
    /// <summary>
    /// 获取指定键的值或默认值
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="keyValues"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static TValue? GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> keyValues, TKey key)
        where TKey : notnull
    {
        return keyValues.TryGetValue(key, out var value) ? value : default;
    }

    /// <summary>
    /// 获取指定键的值或默认值,可设置默认值
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="keyValues"></param>
    /// <param name="key"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> keyValues, TKey key,
        TValue defaultValue) where TKey : notnull
    {
        return keyValues.TryGetValue(key, out var value) ? value : defaultValue;
    }

    /// <summary>
    /// 获取指定键的字符串类型值或默认值
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="keyValues"></param>
    /// <param name="key"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static string GetStringValue<TKey, TValue>(this Dictionary<TKey, TValue> keyValues, TKey key,
        string defaultValue) where TKey : notnull
    {
        if (keyValues.TryGetValue(key, out var value))
        {
            return value?.ToString() ?? "";
        }
        else
        {
            return defaultValue;
        }
    }

    /// <summary>
    /// 批量添加
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="keyValues"></param>
    /// <param name="values"></param>
    /// <returns></returns>
    public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> keyValues,
        Dictionary<TKey, TValue> values) where TKey : notnull
    {
        foreach (var value in values)
        {
            keyValues.TryAdd(value.Key, value.Value);
        }

        return keyValues;
    }
}